import { PointerInfo } from '@babylonjs/core/Events/pointerEvents';
import { Scene } from '@babylonjs/core/scene';
import { Vector3 } from '@babylonjs/core/Maths/math.vector';
import { Axis } from '@babylonjs/core/Maths/math.axis';
import { PickingInfo } from '@babylonjs/core/Collisions/pickingInfo';


const ref_left = new Vector3();
const ref_down = new Vector3();
const vertical = new Vector3();
const horizontal = new Vector3();


interface ISettedInfo {
    x: number,
    y: number,
}


interface ISettedPointerInfo {
    type: number,
    event: ISettedInfo,
    pickInfo?: PickingInfo,
}


const event: ISettedPointerInfo = {
    event: { x: 0, y: 0 },
    pickInfo: undefined,
    type: 0,
};


/**
 * 沉浸模式下模拟页面触点位置事件
 * @param e 原始事件
 * @param scene 所在场景
 * @returns 模拟计算后的事件
 */
const SetPointerEvent = (e: PointerInfo, scene: Scene): PointerInfo => {
    if (!e.pickInfo) return e;
    if (!e.pickInfo.ray) return e;
    if ((e.event as PointerEvent).pointerType !== 'xr') return e;
    const camera = scene.activeCamera?.rigCameras[0];
    if (!camera) return e;

    const w = scene.getEngine().getRenderWidth(true);
    const h = scene.getEngine().getRenderHeight(true);
    const direction = e.pickInfo.ray.direction;

    camera.getDirectionToRef(Axis.X, ref_left);
    camera.getDirectionToRef(Axis.Y, ref_down);
    ref_down.negateInPlace();

    Vector3.ReflectToRef(direction, ref_left, vertical);
    const dy = Vector3.Dot(vertical, ref_down);

    Vector3.ReflectToRef(direction, ref_down, horizontal);
    const dx = Vector3.Dot(horizontal, ref_left);

    event.type = e.type;
    event.pickInfo = e.pickInfo;
    event.event = {
        x: (dx + 1) * 0.5 * w,
        y: (dy + 1) * 0.5 * h
    };
    return event as PointerInfo;
};


export { SetPointerEvent };